package com.miniapp.utils;
 
import com.miniapp.constant.SysConstants;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;
import sun.net.ftp.FtpProtocolException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * FtpUtil工具类 ftp文件上传类
 *
 * @Author linyuchi
 * @Date 2018-05-09
 */
@Component
public class FtpUtil {
    public static boolean uploadFile(String originFileName, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("utf-8");
        try {
            int reply;
            ftp.connect(SysConstants.FTP_ADDRESS, SysConstants.FTP_PORT);
            ftp.login(SysConstants.FTP_USERNAME, SysConstants.FTP_PASSWORD);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.makeDirectory(SysConstants.FTP_BASEPATH);
            ftp.changeWorkingDirectory(SysConstants.FTP_BASEPATH);
            ftp.enterLocalPassiveMode();
            ftp.storeFile(originFileName, input);
            input.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }
    public static void main(String[] args) throws Exception {
        FtpUtil.uploadFile("123.txt",new FileInputStream(new File("B://123.txt")));
    }
}
